package com.helpdesk.controllers;

import com.helpdesk.beans.CategoriesLazyModel;
import com.helpdesk.beans.PostLazyModel;
import com.helpdesk.entities.Posts;
import com.helpdesk.controllers.util.JsfUtil;
import com.helpdesk.controllers.util.PaginationHelper;
import com.helpdesk.beans.PostsFacade;
import com.helpdesk.entities.Accounts;
import java.io.FileNotFoundException;
import java.io.IOException;

import java.io.Serializable;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.UploadedFile;

@ManagedBean(name = "postsController")
@SessionScoped
public class PostsController implements Serializable {

    private Posts current;
    private DataModel items = null;
    private LazyDataModel<Posts> posts;
    @EJB
    private com.helpdesk.beans.PostsFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private Object controller;

    public PostsController() {
    }

    public Posts getSelected() {
        if (current == null) {
            current = new Posts();
            selectedItemIndex = -1;
        }
        return current;
    }

    public void setSelected(Posts posts)
    {
        current = posts;
    }
    
    private PostsFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "listpost";
    }

    public String prepareView() {
//        current = (Posts) getItems().getRowData();
//        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "view_post";
    }

    public String prepareCreate() {
        current = new Posts();
        selectedItemIndex = -1;
        return "new";
    }

    public String create() {
        try {
            HttpSession session = JsfUtil.getSession(true);
            Accounts acc = (Accounts) session.getAttribute(LoginController.currentUserKey);
//            AccountsController  controller = (AccountsController) JsfUtil.getController("accountsController");
//            Accounts id = acc.getUsername();
            current.setAccountID(acc);
            current.setDateCreated(new Date());
            current.setLastUpdate(new Date());
            getFacade().create(current);
            JsfUtil.addSuccessMessage("PostsCreated");
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, "PersistenceErrorOccured");
            return null;
        }
    }

    public String prepareEdit() {
//        current = (Posts) getItems().getRowData();
//        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "edit";
    }

    public String update() {
        try {
            current.setLastUpdate(new Date());
            getFacade().edit(current);
            JsfUtil.addSuccessMessage("PostsUpdated");
            return "edit";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, "PersistenceErrorOccured");
            return null;
        }
    }

    public String destroy() {
//        current = (Posts) getItems().getRowData();
//        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
//        recreatePagination();
//        recreateModel();
        return "listpost";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            RequestContext requestContext = RequestContext.getCurrentInstance();
            requestContext.addCallbackParam("item",current.getId());
            JsfUtil.addSuccessMessage("PostsDeleted");
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, "PersistenceErrorOccured");
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        posts = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }
    
    public void handleFileUpload(FileUploadEvent event) {
        try {
            UploadedFile _uploadedFile = event.getFile();
            String fileName = JsfUtil.saveImageFile(_uploadedFile);
            current.setImg(fileName);
            FacesMessage msg = new FacesMessage("Succesful", fileName + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(FileUploadController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FileUploadController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * @return the posts
     */
    public LazyDataModel<Posts> getPosts() {
        if (posts == null) {
            posts = new PostLazyModel(getFacade().findAll());
        }
        return posts;
    }

    /**
     * @param posts the posts to set
     */
    public void setPosts(LazyDataModel<Posts> posts) {
        this.posts = posts;
    }

    @FacesConverter(forClass = Posts.class)
    public static class PostsControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            PostsController controller = (PostsController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "postsController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Posts) {
                Posts o = (Posts) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Posts.class.getName());
            }
        }
    }
}
